<template>
  <div class="container">
    <!-- 上方统计数据展示部分 -->
    <div>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card shadow="always">
            <el-statistic :value="statisticsData.total">
              <template #title>
                <div style="display: inline-flex; align-items: center">总申请数</div>
              </template>
            </el-statistic>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="always">
            <el-statistic :value="statisticsData.wait">
              <template #title>
                <div style="display: inline-flex; align-items: center">待审核</div>
              </template>
            </el-statistic>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="always">
            <el-statistic :value="statisticsData.supplement">
              <template #title>
                <div style="display: inline-flex; align-items: center">待补充</div>
              </template>
            </el-statistic>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <!-- 数据展示部分 -->
    <div style="margin-top: 20px; padding: 20px; background-color: white">
      <el-form :model="serchOptions">
        <!-- 搜索项 -->
        <div class="search-container">
          <el-space wrap direction="horizontal" class="search-items">
            <el-form-item>
              <el-input v-model="serchOptions.name" placeholder="请输入申请人姓名" class="input-with-select">
                <template #append>
                  <el-button :icon="Search" @click="handleSearch(serchOptions)" />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-input v-model="serchOptions.serviceItemName" placeholder="请输入项目名称" class="input-with-select">
                <template #append>
                  <el-button :icon="Search" @click="handleSearch(serchOptions)" />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <!-- 这里需要设置一下宽度，目前下面组件宽度会丢失 -->
              <el-select
                v-model="serchOptions.statusList"
                style="width: 180px"
                multiple
                collapse-tags
                collapse-tags-tooltip
                placeholder="请选择状态"
                @change="handleSearch(serchOptions)"
              >
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-date-picker
                v-model="applyTimeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="起始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-space>

          <!-- 操作按钮区域 -->
          <div class="action-buttons">
            <el-button @click="handleRefresh">
              <el-icon><Refresh /></el-icon>
              刷新数据
            </el-button>
          </div>
        </div>
      </el-form>
      <!-- 表格部分 -->
      <el-table :data="tableData" height="400" style="width: 100%; margin-top: 10px">
        <el-table-column prop="name" label="申请人">
          <template #default="scope">
            <el-space>
              <el-avatar size="medium" :src="scope.row.avatar" />
              <span>{{ scope.row.name }}</span>
            </el-space>
          </template>
        </el-table-column>
        <el-table-column prop="serviceItemName" label="申请项目" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="statusColor(scope.row.status)">{{ showStatus(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="申请日期">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleDetailDialogClick(scope.row)"> 查看 </el-button>
            <el-button
              v-if="scope.row.status === 0"
              size="small"
              type="primary"
              @click="handleAuditDialogClick(scope.row)"
            >
              审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页部分 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        style="margin-top: 20px"
        :page-sizes="[5, 10, 20, 30, 40]"
        size="default"
        layout="total, sizes, prev, pager, next"
        :total="total"
      />
    </div>
  </div>

  <!-- 申请详情模态框 -->
  <el-dialog v-model="detailDialogVisible" title="申请详情" align-center>
    <template #header>
      <h3 style="text-align: center">申请详情</h3>
    </template>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-space direction="vertical" alignment="stretch" style="width: 100%">
          <el-card shadow="always">
            <!-- title -->
            <div>
              <el-icon><User /></el-icon>
              <span>申请人信息</span>
            </div>
            <!-- 申请者信息 -->
            <el-space direction="vertical" style="margin-top: 20px">
              <el-space>
                <el-avatar :size="100" :src="detailDialogData.avatar" />
                <span>{{ detailDialogData.name }}</span>
              </el-space>
            </el-space>
          </el-card>
          <el-card shadow="always">
            <template #header>
              <el-space>
                <el-icon><PictureFilled /></el-icon>
                <span>申请材料</span>
              </el-space>
            </template>
            <!-- 资格证书图片 -->
            <el-space direction="horizontal" wrap style="margin-top: 20px">
              <el-image
                v-for="(item, index) in detailDialogData.certificatePhotos"
                :key="index"
                style="width: 100px; height: 100px; cursor: pointer"
                :src="item"
                fit="fill"
                :preview-src-list="detailDialogData.certificatePhotos"
                :initial-index="index"
                preview-teleported
                hide-on-click-modal
              />
            </el-space>
          </el-card>
        </el-space>
      </el-col>
      <el-col :span="12">
        <el-card shadow="always">
          <el-space>
            <el-icon><Document /></el-icon>
            <span>申请项目信息</span>
          </el-space>
          <!-- 申请项目信息 -->
          <el-space direction="vertical" alignment="flex-start" style="margin-top: 20px; width: 100%">
            <el-space>
              <span>申请项目：</span>
              <strong>{{ detailDialogData.serviceItemName }}</strong>
            </el-space>
            <el-space>
              <span>所属科目：</span>
              <strong>{{ detailDialogData.serviceItemName }}</strong>
            </el-space>
            <el-space>
              <span>申请状态：</span>
              <el-tag :type="statusColor(detailDialogData.status)">{{ showStatus(detailDialogData.status) }}</el-tag>
            </el-space>
            <el-space>
              <span>申请日期：</span>
              <strong>{{ detailDialogData.createTime }}</strong>
            </el-space>
          </el-space>
        </el-card>
        <el-card shadow="always" style="margin-top: 10px">
          <el-space fill direction="vertical" style="width: 100%">
            <el-space>
              <el-icon><PriceTag /></el-icon>
              <div>服务项目费用</div>
            </el-space>
            <!-- 服务项目费用 -->
            <el-space direction="vertical" alignment="flex-start">
              <el-statistic :value="detailDialogData.price" value-style="color: #ff6600;font-size: 20px">
                <template #prefix>
                  <el-text style="font-size: 15px">项目费用：¥</el-text>
                </template>
              </el-statistic>
              <el-statistic :value="formatPrice(detailDialogData.fee)" value-style="color: #ff6600;font-size: 20px">
                <template #prefix>
                  <el-text style="font-size: 15px">问诊费用：¥</el-text>
                </template>
              </el-statistic>
            </el-space>
          </el-space>
          <template #footer>
            <el-statistic :value="formatPrice(detailDialogData.totalFee)" value-style="color: #ff6600;font-size: 20px">
              <template #prefix>
                <el-text style="font-size: 15px">总计费用：¥</el-text>
              </template>
            </el-statistic>
          </template>
        </el-card>
      </el-col>
    </el-row>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 审核模态框 -->
  <el-dialog v-model="auditDialogVisible" title="审核" align-center>
    <template #header>
      <h3 style="text-align: center">审核</h3>
    </template>
    <el-form ref="auditFormRef" :model="auditForm">
      <el-space direction="vertical" fill style="width: 100%">
        <!-- 申请信息概览 -->
        <el-card shadow="always">
          <template #header>
            <el-space style="width: 100%">
              <el-icon><Document /></el-icon>
              <span>申请信息概览</span>
            </el-space>
          </template>
          <el-row justify="space-around" :gutter="20">
            <el-col :span="12">
              <el-space>
                <el-avatar :size="50" :src="auditDialogData.avatar" />
                <strong>{{ auditDialogData.name }}</strong>
              </el-space>
            </el-col>
            <el-col :span="12">
              <el-space direction="vertical" alignment="flex-start">
                <el-space direction="horizontal">
                  <el-icon><Folder /></el-icon>
                  <el-text type="primary">{{ auditDialogData.serviceItemName }}</el-text>
                </el-space>
                <el-space direction="horizontal">
                  <el-icon><Calendar /></el-icon>
                  <el-text>{{ auditDialogData.createTime }}</el-text>
                </el-space>
              </el-space>
            </el-col>
          </el-row>
        </el-card>
        <!-- 审核操作 -->
        <el-card shadow="always" style="margin-top: 10px">
          <template #header>
            <el-space>
              <el-text type="danger">*</el-text>
              <el-icon><PriceTag /></el-icon>
              <div>审核操作</div>
            </el-space>
          </template>
          <el-form-item prop="status" required :rules="[{ required: true, message: '请选择审核操作' }]">
            <el-radio-group v-model="auditForm.status" fill="rgb(0, 0, 0)" style="width: 100%" size="large">
              <el-radio value="1" style="min-height: 60px; width: 100%; margin: 0" :border="true">
                <template #default>
                  <el-space direction="horizontal" alignment="center">
                    <el-icon style="font-size: 20px"><Check /></el-icon>
                    <el-space direction="vertical" :size="0" alignment="flex-start">
                      <el-text type="success">审核通过</el-text>
                      <el-text type="info">申请符合要求，审核通过</el-text>
                    </el-space>
                  </el-space>
                </template>
              </el-radio>
              <el-radio value="2" style="min-height: 60px; width: 100%; margin: 0; margin-top: 10px" :border="true">
                <template #default>
                  <el-space direction="horizontal" alignment="center">
                    <el-icon style="font-size: 20px"><Close /></el-icon>
                    <el-space direction="vertical" :size="0" alignment="flex-start">
                      <el-text type="danger">拒绝申请</el-text>
                      <el-text type="info">申请不符合要求，拒绝通过</el-text>
                    </el-space>
                  </el-space>
                </template>
              </el-radio>
              <el-radio value="3" style="min-height: 60px; width: 100%; margin: 0; margin-top: 10px" :border="true">
                <template #default>
                  <el-space direction="horizontal" alignment="center">
                    <el-icon style="font-size: 20px"><EditPen /></el-icon>
                    <el-space direction="vertical" :size="0" alignment="flex-start">
                      <el-text type="warning">需要补充材料</el-text>
                      <el-text type="info">申请材料不完整，需要补充材料</el-text>
                    </el-space>
                  </el-space>
                </template>
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-card>
      </el-space>
      <!-- 审核意见 -->
      <el-card shadow="always" style="margin-top: 10px">
        <template #header>
          <el-space>
            <el-text type="danger">*</el-text>
            <el-icon><Edit /></el-icon>
            <div>审核意见</div>
          </el-space>
        </template>
        <el-form-item
          prop="checkOpinion"
          required
          :rules="[
            { required: true, message: '请输入审核意见' },
            { max: 400, message: '审核意见不能超过400个字符' },
            { min: 1, message: '审核意见不能少于1个字符' },
            { pattern: /\S/, message: '审核意见不能为空' },
          ]"
        >
          <el-space direction="vertical" fill style="width: 100%">
            <el-input
              v-model="auditForm.checkOpinion"
              :show-word-limit="true"
              resize="none"
              :autosize="{ minRows: 2, maxRows: 4 }"
              maxlength="400"
              type="textarea"
              placeholder="例如：申请材料齐全，符合要求，予以通过。"
            />
          </el-space>
        </el-form-item>
        <template #footer>
          <!-- 提示信息 -->
          <el-alert :closable="false" style="margin-top: 10px">
            <template #default>
              <el-space direction="vertical">
                <el-space>
                  <el-icon color="#ffc345"><Opportunity /></el-icon>
                  <span>提示：请提供具体的审核意见，以便申请人了解审核结果</span>
                </el-space>
              </el-space>
            </template>
          </el-alert>
        </template>
      </el-card>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="auditDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="submitAudit">确认审核</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import type { BreedingStats, serviceItemRequest, serviceItemResponse } from '@/api/model/serviceItemRequest';
import {
  getBreedingStats,
  getServiceItemRequestDetail,
  getServiceItemRequestList,
  updateServiceItemRequest,
} from '@/api/serviceItemRequest';
import { formatDate } from '@/utils/date';
import { Search } from '@element-plus/icons-vue';
import type { FormInstance } from 'element-plus';
import { ElMessage } from 'element-plus';
import { onActivated, ref, watch } from 'vue';

defineOptions({
  name: 'ServiceItemRequestIndex',
});

const tableData = ref<serviceItemResponse[]>([]);

// 统计数据
const statisticsData = ref<BreedingStats>({
  total: 0,
  wait: 0,
  supplement: 0,
});

// 时间范围
const applyTimeRange = ref<string[]>([]);

// 搜索表单
const serchOptions = ref<serviceItemRequest>({
  name: '',
  serviceItemName: '',
  statusList: [],
});

// 分页参数
const total = ref(100);
const currentPage = ref(1);
const pageSize = ref(10);

// 状态选项
const statusOptions = ref([
  { label: '待审核', value: 0 },
  { label: '已通过', value: 1 },
  { label: '已拒绝', value: 2 },
  { label: '待补充', value: 3 },
]);

// 防抖函数
const debounce = (func: Function, delay: number) => {
  let timeoutId: NodeJS.Timeout;
  return (...args: any[]) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func.apply(null, args), delay);
  };
};

// 搜索处理函数
const handleSearch = (options: serviceItemRequest) => {
  console.log('搜索参数:', options);
  // 更新搜索参数并重新获取数据
  fetchDataWithSearch();
};

// 带搜索条件的数据获取函数
const fetchDataWithSearch = async () => {
  try {
    const searchParams = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...serchOptions.value,
      beginTime: applyTimeRange.value && applyTimeRange.value.length > 0 ? applyTimeRange.value[0] : undefined,
      endTime: applyTimeRange.value && applyTimeRange.value.length > 1 ? applyTimeRange.value[1] : undefined,
    };

    console.log('搜索参数:', searchParams); // 添加日志以便调试

    const res = await getServiceItemRequestList(searchParams);
    tableData.value = res.data.data.records;
    total.value = res.data.data.total;
  } catch (error) {
    console.error('获取服务项目申请列表失败:', error);
    ElMessage.error('获取列表数据失败');
  }
};

// 创建防抖的搜索函数
const debouncedSearch = debounce(handleSearch, 400);

// 监听搜索条件变化，实现实时搜索
watch(
  [() => serchOptions.value.name, () => serchOptions.value.serviceItemName, () => serchOptions.value.status],
  () => {
    // 使用防抖搜索
    debouncedSearch(serchOptions.value);
  },
  { deep: true },
);

// 监听时间范围变化
watch(
  applyTimeRange,
  () => {
    // 使用防抖搜索
    debouncedSearch(serchOptions.value);
  },
  { deep: true },
);

// 监听分页参数变化，使用 watch 实现双向绑定
watch(
  [currentPage, pageSize],
  () => {
    // 重新获取数据
    fetchDataWithSearch();
  },
  { immediate: false },
);

const detailDialogVisible = ref(false);

// 根据状态设置不同的tag颜色
const statusColor = (status: number) => {
  if (status === 0) {
    return 'warning';
  } else if (status === 1) {
    return 'success';
  } else if (status === 2) {
    return 'danger';
  } else if (status === 3) {
    return 'info';
  } else {
    return 'default';
  }
};
// 当前选中的申请详情数据
const detailDialogData = ref<serviceItemResponse>(null);

const handleDetailDialogClick = (row: serviceItemResponse) => {
  getServiceItemRequestDetail(row.id).then((res) => {
    detailDialogData.value = res.data.data;
    detailDialogVisible.value = true;
  });
};

const auditDialogVisible = ref(false);
// 当前选中的审核数据
const auditDialogData = ref<serviceItemResponse | null>(null);

const handleAuditDialogClick = (row: serviceItemResponse) => {
  // 直接使用表格行数据
  auditDialogData.value = row;
  // 初始化审核表单
  auditForm.value.id = row.id;
  auditForm.value.status = '';
  auditForm.value.checkOpinion = '';
  auditDialogVisible.value = true;
};

// 审核表单实例
const auditFormRef = ref<FormInstance>();
// 审核表单
const auditForm = ref({
  id: 0,
  status: '',
  checkOpinion: '',
});
// 提交审核
const submitAudit = async () => {
  auditFormRef.value?.validate(async (valid) => {
    if (valid) {
      console.log('审核表单数据', auditForm.value);
      const updateData: serviceItemRequest = {
        id: auditForm.value.id,
        status: Number(auditForm.value.status),
        checkOpinion: auditForm.value.checkOpinion,
      };
      try {
        // 向后端发送表单
        await updateServiceItemRequest(updateData);
        ElMessage.success('审核成功');
        auditDialogVisible.value = false;
        fetchStatisticsData();
        fetchData();
      } catch (error) {
        console.error('审核失败:', error);
        ElMessage.error('审核失败，请稍后重试');
      }
    }
  });
};
const showStatus = (status: number) => {
  return statusOptions.value.find((item) => item.value === status)?.label;
};

// 分 → 元，去掉尾部无意义的 0
const formatPrice = (cents?: number | string | null): string => {
  if (cents == null || cents === '' || Number.isNaN(cents)) return '0';
  const y = Number(cents) / 100; // 转元
  if (!Number.isFinite(y)) return '0'; // 防 Infinity/NaN
  return y
    .toFixed(2) // 先保留 2 位
    .replace(/\.?0+$/, '') // 去掉小数点后全 0
    .replace(/\.$/, ''); // 如果小数点成孤儿，也删掉
};

const fetchStatisticsData = async () => {
  try {
    const res = await getBreedingStats();
    statisticsData.value = res.data.data;
  } catch (error) {
    console.error('获取繁育统计数据失败:', error);
    ElMessage.error(error.message || '获取统计数据失败');
  }
};

const fetchData = async () => {
  // 使用带搜索条件的数据获取函数
  await fetchDataWithSearch();
};

// 刷新数据
const handleRefresh = () => {
  currentPage.value = 1;
  fetchStatisticsData();
  fetchData();
};

// 页面加载时获取数据
onActivated(() => {
  fetchStatisticsData();
  fetchData();
});
</script>
<style scoped>
/* 搜索容器样式 */
.search-container {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  gap: 16px;
  justify-content: space-between;
}

.search-items {
  flex: 1;
  min-width: 0; /* 防止flex子项溢出 */
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-shrink: 0; /* 防止按钮区域被压缩 */
  align-items: flex-start;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-container {
    flex-direction: column;
    align-items: stretch;
  }

  .action-buttons {
    justify-content: flex-end;
    margin-top: 8px;
  }
}

@media (max-width: 768px) {
  .action-buttons {
    flex-wrap: wrap;
    justify-content: center;
  }

  .action-buttons .el-button {
    flex: 1;
    min-width: 100px;
  }
}

@media (max-width: 480px) {
  .action-buttons {
    flex-direction: column;
  }

  .action-buttons .el-button {
    width: 100%;
  }
}

/**
 * 审核操作，对应选中的颜色变化
 */
/* 审核通过 */
label.el-radio.is-bordered.is-checked.el-radio--large:nth-child(1) {
  background-color: #f0f9f6;
  border-color: #00a870;
}
/* 拒绝申请 */
label.el-radio.is-bordered.is-checked.el-radio--large:nth-child(2) {
  border-color: #f56c6c;
  background-color: #fff0f0;
}
/* 待补充 */
label.el-radio.is-bordered.is-checked.el-radio--large:nth-child(3) {
  border-color: #e6a23c;
  background-color: #fff8e6;
}
/* 使用deep选择器，因为使用scope会默认添加前缀，导致不匹配 */
/* :deep(.el-radio__input.is-checked .el-radio__inner) {
  background: #ff6600;
  border-color: #ff6600;
} */
</style>
